import { useDictSync } from "@/composables/useDictSync";
import { Auth } from "@/utils/auth";

// 全局 WebSocket 实例管理
const websocketInstances = new Map<string, any>();

// 状态标记
let isInitialized = false;
let dictWebSocketInstance: ReturnType<typeof useDictSync> | null = null;

/**
 * 注册 WebSocket 实例
 */
export function registerWebSocketInstance(key: string, instance: any) {
  websocketInstances.set(key, instance);
  console.log(`[WebSocketPlugin] Registered WebSocket instance: ${key}`);
}

/**
 * 获取 WebSocket 实例
 */
export function getWebSocketInstance(key: string) {
  return websocketInstances.get(key);
}

/**
 * 初始化WebSocket服务
 */
export function setupWebSocket() {
  console.log("[WebSocketPlugin] 开始初始化WebSocket服务...");

  if (isInitialized) {
    console.log("[WebSocketPlugin] 已初始化,跳过重复执行");
    return;
  }

  const wsEndpoint = import.meta.env.VITE_APP_WS_ENDPOINT;
  if (!wsEndpoint) {
    console.log("[WebSocketPlugin] 未配置端点,跳过初始化");
    return;
  }

  if (!Auth.isLoggedIn()) {
    console.warn("[WebSocketPlugin] 未登录,跳过初始化");
    return;
  }

  try {
    setTimeout(() => {
      // 1. 字典同步 WebSocket
      dictWebSocketInstance = useDictSync();
      registerWebSocketInstance("dictSync", dictWebSocketInstance);
      dictWebSocketInstance.initWebSocket();
      console.log("[WebSocketPlugin] 字典WebSocket初始化完成");

      // 2. 在线用户计数 WebSocket
      import("@/composables/useOnlineCount").then(({ useOnlineCount }) => {
        const onlineCountInstance = useOnlineCount({ autoInit: false });
        onlineCountInstance.initWebSocket();
        registerWebSocketInstance("onlineCount", onlineCountInstance);
        console.log("[WebSocketPlugin] 在线用户WebSocket初始化完成");
      });

      // 3. 系统资源监控 WebSocket（新增）
      import("@/composables/useSystemMonitor").then(({ useSystemMonitor }) => {
        const systemMonitorInstance = useSystemMonitor();
        systemMonitorInstance.initWebSocket();
        registerWebSocketInstance("systemMonitor", systemMonitorInstance);
        console.log("[WebSocketPlugin] 系统监控WebSocket初始化完成");
      });

      // 窗口关闭处理
      window.addEventListener("beforeunload", handleWindowClose);

      isInitialized = true;
      console.log("[WebSocketPlugin] 所有WebSocket服务初始化完成");
    }, 1000);
  } catch (error) {
    console.error("[WebSocketPlugin] 初始化失败:", error);
  }
}

/**
 * 处理窗口关闭
 */
function handleWindowClose() {
  console.log("[WebSocketPlugin] 窗口关闭,清理连接");
  cleanupWebSocket();
}

/**
 * 清理WebSocket连接
 */
export function cleanupWebSocket() {
  // 清理字典连接
  if (dictWebSocketInstance) {
    try {
      dictWebSocketInstance.closeWebSocket();
      console.log("[WebSocketPlugin] 字典连接已断开");
    } catch (e) {
      console.error("[WebSocketPlugin] 字典连接断开失败:", e);
    }
  }

  // 清理所有注册实例
  websocketInstances.forEach((instance, key) => {
    try {
      if (instance.closeWebSocket) {
        instance.closeWebSocket();
      } else if (instance.disconnect) {
        instance.disconnect();
      }
      console.log(`[WebSocketPlugin] ${key} 连接已断开`);
    } catch (e) {
      console.error(`[WebSocketPlugin] ${key} 连接断开失败:`, e);
    }
  });

  // 重置状态
  websocketInstances.clear();
  window.removeEventListener("beforeunload", handleWindowClose);
  dictWebSocketInstance = null;
  isInitialized = false;
}

/**
 * 重新初始化WebSocket（登录后调用）
 */
export function reinitializeWebSocket() {
  cleanupWebSocket();
  setTimeout(setupWebSocket, 500);
}
